package heman.common;
/**
 * This does basic authorization.
 * A Player cannot login twice!!!
 * (However, the "admin" account can for the convenience of test. 
 *   @author Wenlong Liu
 */


import heman.server.database.DatabaseController;
import heman.server.entities.PlayerManager;
import heman.server.entities.TableManager;
import ks.client.ipc.Client;
import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.interfaces.IAuthorization;

public class Authorization implements IAuthorization{
	private Authorization(){
		//Authorization uses singleton just because of this
		DatabaseController.init();
	}
	@Override
	public boolean authorize(String who, String pwd) throws Exception {
		// TODO Auto-generated method stub
		if (pwd.equals(Client.sha1("admin")) && PlayerManager.getInstance().getPlayer(who)==null) return true;
		//This might not be in the Authorization
		//Actually it should be in the login controller
		//But consider the efficiency of the server
		//boolean b=DatabaseController.checkBan(who);
		if (PlayerManager.getInstance().getPlayer(who)!=null ||
				//the player's game does not end before it logs in again
				TableManager.getInstance().onTable(who)!=null
				|| DatabaseController.checkBan(who)
			) return false;
		
		return DatabaseController.getPsw(who).equals(pwd);
	}

	@Override
	public String selfRegister(String password) {
		// TODO Auto-generated method stub
		//int len=password.length();
		String selfString=DatabaseController.newPlayer(password);
		return selfString;
	}

	@Override
	public void login(Communicator com, Message m) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void logout(Communicator com, Message m) {
		// TODO Auto-generated method stub
		
	}
	public static Authorization getInstance(){
		if (auth==null)
			synchronized (Authorization.class) {
				if (auth==null)
					return auth=new Authorization();
				else return auth;
			}
			
		
		return auth;
	
	}
	private static Authorization auth=null;
}
